import { useContext, useEffect, useState } from 'react';
import { Button, Spin, Table, message, Space, Row } from 'antd';
import lodash from 'lodash';
import { history } from 'umi';
import { getPackTableColumns } from '../mconfig';
import { IUpdateEnum } from '../common/UpdateReducer';
import { addBidService, findSourceInviteService, postponeService } from '../services/UpdateService';
import { BZWC_STATE, CQXG_STATE, LB_STATE, YDB_STATE, generateRandomNumber, returnPurchaseTypeList } from '../common/Format';

import moment from 'moment';
import { UpCircleOutlined, EditOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { SourceUpdateContext } from '../common/UpdateContext';
import { Descriptions, useDescriptions } from '@/components/Descriptions';
import { sortCreateTimeData } from '../../Acommon';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import { readReadShowFileService } from '@/services/BaseLayout';
import { getBaseUrl } from '@/services/urlconst';
import { getInvoiceCode } from '@/utils';

/** 招标公告 */
const UpdateSourceInviteView = () => {
  /** 上下文 */
  const { Source_Invite, locationProps, dispatch, curRes } = useContext(SourceUpdateContext);
  /**获取路由信息*/
  const { info = {}, type, sourceKey } = locationProps?.state || {};
  /** 标包数据 */
  const [packDataSource, setPackDataSource] = useState<Record<string, any>[]>([]);
  /** 选择申请下的标包数据的拟定采购方式集合 */
  const [packBnstList, setPackBnstList] = useState<Record<string, any>[]>([]);
  /** 选择下来的采购类型 */
  const [selType, setSetType] = useState<string>('');
  /** 保存一下type，区分是新增还是eidt */
  const [isType, setIsType] = useState<string>('add');
  /** 实施详情保存一份 */
  const [infoObj, setInfoObj] = useState<Record<string, any>>({});
  /** 开标时间 */
  const [KTime, setKTime] = useState<string>('');
  /** 澄清截至日期 */
  const [CTime, setCTime] = useState<string>('');
  /** 招标文件开始 */
  const [BDStartTime, setBDStartTime] = useState<string>('');
  /** 招标文件开始 */
  const [BDEndTime, setBDEndTime] = useState<string>('');
  /** 公告的提交弹窗 */
  const [isShowSubmitModal, setIsShowSubmitModal] = useState<Record<string, any>>({
    isShow: false,
    resObj: null,
  });

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
    // readReadShowFileRun({ fieldPath: `http://222.186.101.211:20103${fieldUrl}` });
  };

  /** 拟采用采购方式的下拉选择事件 */
  const onSupplyTypeSelect = (value) => {
    setSetType(value);
  };

  /** @config 表格表单配置 @methods 表格表单方法*/
  const [config, methods] = useDescriptions({
    name: 'source-invite',
    labelWidth: 250,
    schemas: [
      {
        label: '一、公告详情',
        field: 'Title',
        component: 'Title',
      },
      {
        label: '公告名称',
        field: 'noticeName',
        component: 'Input',
        placeholder: '请输入',
        required: true,
        message: '请输入',
        disabled: isType === 'edit',
      },
      {
        label: '公告编号',
        field: 'noticeCode',
        component: 'Input',
        disabled: true,
        placeholder: '自动生成',
        initialValue: getInvoiceCode('GG'),
      },
      {
        label: '采购项目名称',
        field: 'purchProjectName',
        component: 'Input',
        placeholder: '请选择',
        required: false,
        message: '请选择',
        // colSpan: 2,
        disabled: true,
      },
      {
        label: '流水单号',
        field: 'purchProjectCode',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '公告日期',
        field: 'noticeTime',
        component: 'DatePicker',
        placeholder: type == 'detail' ? '--' : '请选择',
        required: true,
        message: '请选择',
      },
      {
        label: '拟采用采购方式',
        field: 'binusstypeName',
        component: 'Select',
        options: packBnstList,
        placeholder: '请选择',
        onSelect: onSupplyTypeSelect,
        showArrow: type == 'detail' ? false : true,
        required: false,
        message: '请选择',
        disabled: true,
      },
      {
        label: '开标日期',
        field: 'bidOpenTime',
        component: 'DatePicker',
        placeholder: type == 'detail' ? '--' : '请选择',
        disabled: isType === 'edit',
        required: true,
        message: '请选择',
        onChange: (val) => {
          if (val) {
            setKTime(moment(val)?.format('YYYY-MM-DD HH:mm:ss'));
          }
        },
        disabledDate: (current) => {
          if (CTime) {
            return current && current < moment(CTime).startOf('days');
          }
        },
      },
      {
        label: '澄清截止日期',
        field: 'bidClearTime',
        component: 'DatePicker',
        placeholder: type == 'detail' ? '--' : '请选择',
        disabled: isType === 'edit',
        required: true,
        message: '请选择',
        onChange: (val) => {
          if (val) {
            setCTime(moment(val)?.format('YYYY-MM-DD HH:mm:ss'));
          }
        },
        disabledDate: (current) => {
          if (KTime) {
            return current && current > moment(KTime).startOf('days');
          }
        },
      },
      {
        label: '获取招标文件开始时间',
        field: 'bidStartTime',
        component: 'DatePicker',
        placeholder: type == 'detail' ? '--' : '请选择',
        required: true,
        disabled: isType === 'edit',
        message: '请选择',
        onChange: (val) => {
          if (val) {
            setBDStartTime(moment(val)?.format('YYYY-MM-DD HH:mm:ss'));
          }
        },
        disabledDate: (current) => {
          if (BDEndTime) {
            return current && current > moment(BDEndTime).startOf('days');
          }
        },
      },
      {
        label: '获取招标文件结束时间',
        field: 'bidEndTime',
        component: 'DatePicker',
        placeholder: type == 'detail' ? '--' : '请选择',
        required: true,
        disabled: isType === 'edit',
        message: '请选择',
        onChange: (val) => {
          if (val) {
            setBDEndTime(moment(val)?.format('YYYY-MM-DD HH:mm:ss'));
          }
        },
        disabledDate: (current) => {
          if (BDStartTime) {
            return current && current < moment(BDStartTime).startOf('days');
          }
        },
      },
    ],
  });

  /** 延期情况 */
  const [postponeConfig, postponeMethods] = useDescriptions({
    name: 'source-invite-postpone',
    labelWidth: 250,
    schemas: [
      {
        label: '三、延期情况',
        field: 'Title',
        component: 'Title',
      },
      {
        label: '（原）报名截止日期',
        field: 'extensionBidEndTimeOld',
        component: 'DatePicker',
        placeholder: '请选择',
        // required: true,
        disabled: true,
        message: '请选择',
        onChange: (val) => {},
        disabledDate: false,
      },
      {
        label: '（新）报名截止日期',
        field: 'extensionBidEndTime',
        component: 'DatePicker',
        placeholder: '请选择',
        // required: true,
        message: '请选择',
        onChange: (val) => {},
        disabledDate: false,
      },
      {
        label: '（原）开标日期',
        field: 'extensionBidOpenTimeOld',
        component: 'DatePicker',
        placeholder: '请选择',
        // required: true,
        disabled: true,
        message: '请选择',
        onChange: (val) => {},
        disabledDate: false,
      },
      {
        label: '（新）开标日期',
        field: 'extensionBidOpenTime',
        component: 'DatePicker',
        placeholder: '请选择',
        // required: true,
        message: '请选择',
        onChange: (val) => {},
        disabledDate: false,
      },
      {
        label: '（原）澄清截至日期',
        field: 'extensionBidClearTimeOld',
        component: 'DatePicker',
        placeholder: '请选择',
        // required: true,
        disabled: true,
        message: '请选择',
        onChange: (val) => {},
        disabledDate: false,
      },
      {
        label: '（新）澄清截至日期',
        field: 'extensionBidClearTime',
        component: 'DatePicker',
        placeholder: '请选择',
        // required: true,
        message: '请选择',
        onChange: (val) => {},
        disabledDate: false,
      },
    ],
  });

  /** 获取招标公告详情services */
  const { findSourceInviteRun, findSourceInviteLoading } = findSourceInviteService();
  const fetchFindSourceInvite = async (params: Record<string, any>) => {
    const result = await findSourceInviteRun(params);
    const { msgFlag, obj } = result;
    if (msgFlag && obj) {
      obj.mpurchaseSourceList = sortCreateTimeData(obj.mpurchaseSourceList); // 根据包号
      setInfoObj(obj); //保存详情
      dispatch({ type: IUpdateEnum?.Set_Source_Invite, payload: obj }); //向上派发，后面要用
      if (sourceKey) {
        onSupplyTypeSelect(info?.procureReal);
        methods?.setFieldsValue({ binusstypeName: info?.procureReal });
      }
      // 表单设置 - 拟采方式下拉框源数据设置
      const procureRealList: any = returnPurchaseTypeList({ list: obj?.mpurchaseSourceList, fields: 'procureReal' });
      setPackBnstList(procureRealList);
      if (obj?.mpurchaseSourceList?.length) {
        //有公告的情况下
        if (obj?.noticeCode && obj?.mpurchaseSourceList?.length) {
          dispatch({ type: IUpdateEnum?.Set_Invite_PackList, payload: obj?.mpurchaseSourceList });
          setIsType('edit'); // 标识

          // 公告表单信息补充
          methods?.setFieldsValue({
            noticeCode: obj?.noticeCode,
            noticeName: obj?.noticeName,
            purchProjectName: obj?.purchProjectName,
            purchProjectCode: obj?.purchProjectCode,
            bidOpenTime: obj?.bidOpenTime ? moment(obj?.bidOpenTime) : null,
            bidClearTime: obj?.bidClearTime ? moment(obj?.bidClearTime) : null,
            bidStartTime: obj?.bidStartTime ? moment(obj?.bidStartTime) : null,
            bidEndTime: obj?.bidEndTime ? moment(obj?.bidEndTime) : null,
            noticeTime: obj?.noticeTime ? moment(obj?.noticeTime) : null,
            binusstypeName: obj?.mpurchaseSourceList?.[0]?.procureReal,
          });

          // 延期表单信息填充
          postponeMethods?.setFieldsValue({
            extensionBidClearTimeOld: obj?.extensionBidClearTime ? moment(obj?.extensionBidClearTime) : null,
            extensionBidClearTime: null,
            extensionBidOpenTimeOld: obj?.extensionBidOpenTime ? moment(obj?.extensionBidOpenTime) : null,
            extensionBidOpenTime: null,
            extensionBidEndTimeOld: obj?.extensionBidEndTime ? moment(obj?.extensionBidEndTime) : null,
            extensionBidEndTime: null,
          });
          // 展示下方表格数据
          setPackDataSource(obj?.mpurchaseSourceList);
        } else {
          // 没有公告的情况下，只设置【采购项目名称、采购项目编号】
          methods?.setFieldsValue({
            purchProjectName: obj?.purchProjectName,
            purchProjectCode: obj?.purchProjectCode,
            binusstypeName: obj?.mpurchaseSourceList?.[0]?.procureReal,
          });
          onSupplyTypeSelect(obj?.procureReal);
        }
      }
    }
  };

  /** 添加公告service */
  const { addBidRun, addBidLoading } = addBidService((res: any) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      fetchFindSourceInvite({
        id: res?.obj?.id,
        noticeCode: res?.obj?.noticeCode,
        applyID: info?.applyID,
      });
      history.push({
        pathname: '/sourceController/manage',
        state: {
          delRouterNameSource: history.location.pathname,
        },
      });
    } else {
      message.error(res?.msg);
    }
  });

  /** 延期情况service */
  const { postponeRun, postponeLoading } = postponeService();

  /** 删除标包 */
  const onRemovePack = (index: number) => {
    const tempData = lodash.cloneDeep(packDataSource);
    tempData.splice(index, 1);
    setPackDataSource(tempData);
  };

  /** 根据拟采用采购方式状态来获取相关标包列表数据 */
  useEffect(() => {
    if (Source_Invite?.mpurchaseSourceList?.length > 0) {
      const modaldata = Source_Invite?.mpurchaseSourceList?.filter((item) => item?.procureReal == selType && item?.state == BZWC_STATE());
      setPackDataSource(modaldata);
    }
  }, [selType]);

  /** 初始化，请求详情 */
  useEffect(() => {
    if (info?.id) {
      fetchFindSourceInvite({
        id: info?.id,
        noticeCode: info?.noticeCode,
        applyID: info?.applyID,
      });
    }
  }, [info?.id, sourceKey]);

  /** 提交按钮 */
  const onSubmit = async () => {
    await methods?.validateFields();
    setIsShowSubmitModal({ isShow: true, resObj: null });
  };

  /** 修改按钮 */
  const onEdit = async () => {
    const formObj = await postponeMethods?.validateFields();

    if (!formObj?.extensionBidClearTime && !formObj?.extensionBidEndTime && !formObj?.extensionBidOpenTime) {
      message?.warn('请填写延期情况信息！');
      return;
    }

    let reqParams = {
      extensionBidClearTime: formObj?.extensionBidClearTime
        ? moment(formObj?.extensionBidClearTime).format('YYYY-MM-DD 00:00:00')
        : moment(formObj?.extensionBidClearTimeOld).format('YYYY-MM-DD 00:00:00'),
      extensionBidEndTime: formObj?.extensionBidEndTime
        ? moment(formObj?.extensionBidEndTime).format('YYYY-MM-DD 00:00:00')
        : moment(formObj?.extensionBidEndTimeOld).format('YYYY-MM-DD 00:00:00'),
      extensionBidOpenTime: formObj?.extensionBidOpenTime
        ? moment(formObj?.extensionBidOpenTime).format('YYYY-MM-DD 00:00:00')
        : moment(formObj?.extensionBidOpenTimeOld).format('YYYY-MM-DD 00:00:00'),
      sourceIDS: packDataSource?.map((item) => item?.id)?.join(',') || null,
    };

    await postponeRun(reqParams)?.then((res) => {
      if (res?.msgFlag) {
        message?.success(res?.msg);
        fetchFindSourceInvite({
          id: info?.id,
          noticeCode: info?.noticeCode,
          applyID: info?.applyID,
        });
      }
    });
  };

  /** 保存按钮 */
  const onSave = () => {
    methods?.validateFields()?.then((values: any) => {
      if (!packDataSource?.length) return message?.warn('请选择招标公告的标包！');
      let payload: Record<string, any> = {
        ...values,
        bidClearTime: values?.bidClearTime ? moment(values?.bidClearTime).format('YYYY-MM-DD 00:00:00') : null,
        bidOpenTime: values?.bidOpenTime ? moment(values?.bidOpenTime).format('YYYY-MM-DD 00:00:00') : null,
        bidStartTime: values?.bidStartTime ? moment(values?.bidStartTime).format('YYYY-MM-DD 00:00:00') : null,
        bidEndTime: values?.bidEndTime ? moment(values?.bidEndTime).format('YYYY-MM-DD 00:00:00') : null,
        noticeTime: values?.noticeTime ? moment(values?.noticeTime).format('YYYY-MM-DD 00:00:00') : null,
        sourceIDS: packDataSource?.map((item) => item?.id)?.join(','),
        id: Source_Invite?.id,
        state: CQXG_STATE(),
      };
      addBidRun(payload);
    });
  };

  const container = () => {
    return (
      <div className={'source-invite'}>
        <Spin spinning={addBidLoading || findSourceInviteLoading || postponeLoading}>
          <ScrollBarLayout>
            <div className={'source-invite-desc'}>
              <Descriptions config={config} />
              <div className={'source-experts-row'}>
                <Row key={'experts'}>
                  <div className={'source-experts-item-title'}>二、相关标包</div>
                  <div className="list-table">
                    <Table
                      bordered
                      size="small"
                      columns={getPackTableColumns({ onOpenReadOfdWord, onRemovePack, pageType: type, isType, infoObj, curRes })}
                      dataSource={packDataSource}
                      scroll={{ x: 500 }}
                      loading={false}
                      rowKey={(record: any) => record?.id}
                      pagination={false}
                    />
                  </div>
                </Row>
              </div>
              {infoObj?.noticeCode && infoObj?.state != BZWC_STATE() && (
                <div style={{ marginTop: 5 }}>
                  <Descriptions config={postponeConfig} />
                </div>
              )}
            </div>
          </ScrollBarLayout>
        </Spin>
        {/* 公告的提交弹窗 */}
        {isShowSubmitModal?.isShow && (
          <TipsErrorModalNew
            bodyWidth={0.25}
            onClose={() => setIsShowSubmitModal({ isShow: false, resObj: null })}
            modalOnOK={onSave}
            modalLoading={addBidLoading}
            // modalTip={'确认提交此次招标公告吗？提交后不可修改!'}
            modalTip={'请确认此次招标公告信息无误，提交后不可修改!'}
          />
        )}
      </div>
    );
  };

  /** 底部操作 */
  const btnFooter = () => {
    return (
      <Space>
        {infoObj?.state == BZWC_STATE() && !infoObj?.noticeCode && curRes?.['/purchaseSourceController/addBid'] && type != 'detail' && (
          <Button
            type="primary"
            // icon={<UpCircleOutlined />}
            onClick={onSubmit}
          >
            提交
          </Button>
        )}
        {curRes?.['/purchaseSourceController/editExtensionBid'] && infoObj?.noticeCode && infoObj?.state != YDB_STATE() && infoObj?.state != LB_STATE() && (
          <Button
            type="primary"
            // icon={<EditOutlined />}
            onClick={onEdit}
          >
            修改
          </Button>
        )}
      </Space>
    );
  };

  return {
    UpdateSourceInvite: container,
    SourceInviteFooter: btnFooter,
    SourceInviteMethods: methods,
    fetchFindSourceInvite,
  };
};

export default UpdateSourceInviteView;
